package demo.threadpool;

import java.util.LinkedList;
import java.util.List;

public class ThreadPool {
	
	private int size;
	
	private List<WorkerThread> pool = new LinkedList<WorkerThread>();
	
	public ThreadPool(int size){
		this.size = size;
		for(int i = 1; i <= size; i++){
			WorkerThread worker = new WorkerThread(this);
			worker.setName("Worker" + i);
			worker.start();
			
			pool.add(worker);
		}
	}
	
	public WorkerThread getWorker(){
		WorkerThread worker = null;
		synchronized(pool){
			if(!pool.isEmpty())
				worker = pool.remove(0);
		}
		return worker;
	}
	
	public void returnWorker(WorkerThread worker){
		synchronized (pool) {
			pool.add(worker);
		}
	}
	
	public int size(){
		return size;
	}
}
